<script lang="ts">
  import { onMount } from 'svelte';
  import axios from 'axios';
  import { t } from '../lib/i18n';
  
  let apiStatus = '正在检查API状态...';
  let apiDetails = '';
  
  // 根据当前环境设置默认API地址
  const isProd = import.meta.env.VITE_MODE === 'production';
  let customApiUrl = isProd ? 'http://localhost:4007' : 'http://localhost:5000';
  
  type TestResult = {
    success: boolean;
    description: string;
    status?: number | string;
    data?: any;
    duration?: number;
    error?: string;
  };
  
  // 测试不同的API端点
  async function testEndpoint(endpoint: string, description: string): Promise<TestResult> {
    try {
      const startTime = performance.now();
      const response = await axios.get(endpoint, { 
        timeout: 5000,
        headers: { 'Cache-Control': 'no-cache' }
      });
      const endTime = performance.now();
      const duration = Math.round(endTime - startTime);
      
      return {
        success: true,
        status: response.status,
        data: response.data,
        duration,
        description
      };
    } catch (error: any) {
      console.error(`测试端点 ${endpoint} 失败:`, error);
      return {
        success: false,
        status: error.response?.status || 'N/A',
        error: error.message,
        description
      };
    }
  }
  
  async function runDiagnostics() {
    apiStatus = '正在测试API连接...';
    apiDetails = '';
    
    const results: TestResult[] = [];
    
    // 测试健康检查端点
    results.push(await testEndpoint('/api/health', '健康检查 API'));
    
    // 测试配置端点
    results.push(await testEndpoint('/api/config', '配置 API'));
    
    // 直接测试后端服务器
    try {
      results.push(await testEndpoint(customApiUrl + '/health', '直接访问后端健康检查'));
    } catch (e: any) {
      results.push({
        success: false,
        description: '直接访问后端健康检查',
        error: e.message
      });
    }
    
    // 显示结果
    const successCount = results.filter(r => r.success).length;
    apiStatus = `测试完成: ${successCount}/${results.length} 成功`;
    
    // 格式化详细信息
    apiDetails = results.map(result => {
      if (result.success) {
        return `✅ ${result.description}: 状态 ${result.status}, 耗时 ${result.duration}ms\n数据: ${JSON.stringify(result.data, null, 2)}`;
      } else {
        return `❌ ${result.description}: 失败 - ${result.error}`;
      }
    }).join('\n\n');
  }
  
  // 检查网络配置
  function checkNetworkConfig() {
    // 根据当前环境获取API地址
    const apiUrl = isProd ? 'http://localhost:4007' : 'http://localhost:5000';
    
    const details = [
      `📍 当前页面URL: ${window.location.href}`,
      `🔌 API代理配置: /api -> ${apiUrl}`,
      `🌐 浏览器: ${navigator.userAgent}`,
      `🔧 环境: ${isProd ? '生产环境' : '开发环境'}`
    ];
    
    apiDetails += '\n\n==== 网络信息 ====\n' + details.join('\n');
  }
  
  function testCustomApi() {
    runDiagnostics();
  }
  
  onMount(() => {
    runDiagnostics();
    checkNetworkConfig();
  });
</script>

<svelte:head>
  <title>{$t('common.debug')}</title>
</svelte:head>

<div class="debug-container">
  <p class="status" class:error={apiStatus.includes('失败')}>
    状态: {apiStatus}
  </p>
  
  <div class="actions">
    <button on:click={runDiagnostics}>重新测试连接</button>
    
    <div class="custom-api">
      <input 
        type="text" 
        bind:value={customApiUrl} 
        placeholder="输入API基础URL" 
      />
      <button on:click={testCustomApi}>测试自定义API</button>
    </div>
  </div>
  
  <div class="results">
    <h3>测试结果</h3>
    <pre>{apiDetails}</pre>
  </div>
  
  <div class="help">
    <h3>故障排除提示</h3>
    <ul>
      <li>确保后端API服务器正在运行并监听正确端口 ({isProd ? '4007' : '5000'})</li>
      <li>检查浏览器控制台中是否有任何CORS错误</li>
      <li>验证您的网络设置允许访问localhost</li>
      <li>确保您的开发环境中没有防火墙阻止连接</li>
    </ul>
  </div>
  
  <div class="links">
    <a href="/">{$t('common.back')}</a>
  </div>
  
  <footer>
    <p>{$t('app.copyright')}</p>
  </footer>
</div>

<style>
  .debug-container {
    max-width: 900px;
    margin: 0 auto;
    padding: 2rem;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  }
  
  .status {
    font-size: 1.2rem;
    padding: 0.75rem;
    background-color: #f0f7ff;
    border-radius: 4px;
    border-left: 4px solid #4a90e2;
    margin-bottom: 1.5rem;
  }
  
  .status.error {
    background-color: #ffebee;
    border-left-color: #f44336;
  }
  
  .actions {
    margin: 1.5rem 0;
    display: flex;
    flex-wrap: wrap;
    gap: 1rem;
    align-items: center;
  }
  
  button {
    background-color: #4a90e2;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
  }
  
  button:hover {
    background-color: #3a80d2;
  }
  
  .custom-api {
    display: flex;
    gap: 0.5rem;
    flex-grow: 1;
  }
  
  input {
    flex-grow: 1;
    padding: 0.5rem;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  
  .results {
    margin: 1.5rem 0;
  }
  
  h3 {
    color: #444;
    font-size: 1.2rem;
    margin-top: 0;
    margin-bottom: 1rem;
  }
  
  pre {
    background-color: #f5f5f5;
    padding: 1rem;
    border-radius: 4px;
    overflow-x: auto;
    white-space: pre-wrap;
    font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
  }
  
  .help {
    background-color: #fffde7;
    padding: 1rem;
    border-radius: 4px;
    margin: 1.5rem 0;
  }
  
  .links {
    margin-top: 2rem;
  }
  
  a {
    color: #4a90e2;
    text-decoration: none;
  }
  
  a:hover {
    text-decoration: underline;
  }
  
  footer {
    margin-top: 2rem;
    text-align: center;
    color: #888;
    font-size: 0.8rem;
    border-top: 1px solid #eee;
    padding-top: 1rem;
  }
</style> 
